package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @auth shanyue
 * @date 2025年06月06日15:29
 */
@Controller
@RequestMapping("/admin/users")
@PreAuthorize("hasRole('ADMIN')")
public class UserController {

    @Resource
    private UserService userService;

    // 用户列表页
    @GetMapping
    public String listUsers(Model model) {
        model.addAttribute("users", userService.listAll());

        // 获取当前登录用户名
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String currentUsername = auth.getName();
        model.addAttribute("currentUsername", currentUsername);

        return "users";
    }

    @PostMapping("/add")
    public String addUser(User user) {
        userService.addUser(user);
        return "redirect:/admin/users";
    }

    @GetMapping("/user_add")
    public String showAddUserPage(Model model) {
        model.addAttribute("user", new User());
        return "admin/user/user_add";
    }


    // 编辑用户提交
    @PostMapping("/edit")
    public String editUser(User user) {
        userService.updateUser(user);
        return "redirect:/admin/users";
    }

    @GetMapping("/edit/{id}")
    public String showEditUserPage(@PathVariable Integer id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "admin/user/user_edit";
    }


    // 删除用户
    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable Integer id) {
        userService.deleteUser(id);
        return "redirect:/admin/users";
    }

}
